
// test_device_sdkDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "test_device_sdk.h"
#include "test_device_sdkDlg.h"
#include "afxdialogex.h"
#include "AviFile.h"
#include "./json/include/json/json.h"
#include "../../../sdk/inc/YhApiDataDef.h"


#ifdef _DEBUG
	#pragma comment(lib, "./json/lib/json_vc71_libmtd.lib")
#else
	#pragma comment(lib, "./json/lib/json_vc71_libmt.lib")
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#endif



FILE* g_file = NULL;

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// Ctest_device_sdkDlg 对话框

Ctest_device_sdkDlg::Ctest_device_sdkDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(IDD_TEST_DEVICE_SDK_DIALOG, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);

	m_hDownload = NULL;
}

void Ctest_device_sdkDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_INFO, m_ctrlInfo);
}

BEGIN_MESSAGE_MAP(Ctest_device_sdkDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_START2, &Ctest_device_sdkDlg::OnBnClickedButtonStart)
	ON_BN_CLICKED(IDC_BUTTON_STOP2, &Ctest_device_sdkDlg::OnBnClickedButtonStop)
	ON_BN_CLICKED(IDC_BUTTON_OPENSTREAM, &Ctest_device_sdkDlg::OnBnClickedButtonOpenstream)
	ON_BN_CLICKED(IDC_BUTTON_CLOSESTREAM, &Ctest_device_sdkDlg::OnBnClickedButtonClosestream)
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_BUTTON_OPENTALK, &Ctest_device_sdkDlg::OnBnClickedButtonOpentalk)
	ON_BN_CLICKED(IDC_BUTTON_CLOSETALK, &Ctest_device_sdkDlg::OnBnClickedButtonClosetalk)
	ON_BN_CLICKED(IDC_BUTTON_GETGPS, &Ctest_device_sdkDlg::OnBnClickedButtonGetgps)
	ON_BN_CLICKED(IDC_BUTTON_STOPGPS, &Ctest_device_sdkDlg::OnBnClickedButtonStopgps)
	ON_BN_CLICKED(IDC_BUTTON_QUERY, &Ctest_device_sdkDlg::OnBnClickedButtonQuery)
	ON_BN_CLICKED(IDC_BUTTON_CLOSEQUERY, &Ctest_device_sdkDlg::OnBnClickedButtonClosequery)
	ON_BN_CLICKED(IDC_BUTTON_SNAP, &Ctest_device_sdkDlg::OnBnClickedButtonSnap)
	ON_BN_CLICKED(IDC_BUTTON_CLOSESNAP, &Ctest_device_sdkDlg::OnBnClickedButtonClosesnap)
	ON_BN_CLICKED(IDC_BUTTON_OPENREPLAY, &Ctest_device_sdkDlg::OnBnClickedButtonOpenreplay)
	ON_BN_CLICKED(IDC_BUTTON_CLOSEREPLAY, &Ctest_device_sdkDlg::OnBnClickedButtonClosereplay)
	ON_BN_CLICKED(IDC_BUTTON_DOWNSNAP, &Ctest_device_sdkDlg::OnBnClickedButtonDownsnap)
	ON_BN_CLICKED(IDC_BUTTON_CLOSEDOWNSNAP, &Ctest_device_sdkDlg::OnBnClickedButtonClosedownsnap)
	ON_BN_CLICKED(IDC_BUTTON_UPGRADE, &Ctest_device_sdkDlg::OnBnClickedButtonUpgrade)
	ON_BN_CLICKED(IDC_BUTTON_CLOSEUPGRADE, &Ctest_device_sdkDlg::OnBnClickedButtonCloseupgrade)
	ON_BN_CLICKED(IDC_BUTTON_GETIOSTATUS, &Ctest_device_sdkDlg::OnBnClickedButtonGetiostatus)
	ON_BN_CLICKED(IDC_BUTTON_IOCTRL, &Ctest_device_sdkDlg::OnBnClickedButtonIoctrl)
	ON_BN_CLICKED(IDC_BUTTON_PTZ, &Ctest_device_sdkDlg::OnBnClickedButtonPtz)
	ON_BN_CLICKED(IDC_BUTTON_TRANS, &Ctest_device_sdkDlg::OnBnClickedButtonTrans)
	ON_BN_CLICKED(IDC_BUTTON_GETALARM, &Ctest_device_sdkDlg::OnBnClickedButtonGetalarm)
	ON_BN_CLICKED(IDC_BUTTON_STOPALARM, &Ctest_device_sdkDlg::OnBnClickedButtonStopalarm)
	ON_BN_CLICKED(IDC_BUTTON_PTZ_TWO, &Ctest_device_sdkDlg::OnBnClickedButtonPtzTwo)
	ON_BN_CLICKED(IDC_BUTTON_SEARCH, &Ctest_device_sdkDlg::OnBnClickedButtonSearch)
	ON_BN_CLICKED(IDC_BUTTON_DIRECTOPENSTREAM, &Ctest_device_sdkDlg::OnBnClickedButtonDirectopenstream)
	ON_BN_CLICKED(IDC_BUTTON_DIRECTCLOSESTREAM, &Ctest_device_sdkDlg::OnBnClickedButtonDirectclosestream)
	ON_BN_CLICKED(IDC_BUTTON_DIRECTPTZ, &Ctest_device_sdkDlg::OnBnClickedButtonDirectptz)
	ON_BN_CLICKED(IDC_BUTTON_STOPSEARCH, &Ctest_device_sdkDlg::OnBnClickedButtonStopsearch)
	ON_BN_CLICKED(IDC_BUTTON_GETCOLOUR, &Ctest_device_sdkDlg::OnBnClickedButtonGetcolour)
	ON_BN_CLICKED(IDC_BUTTON_SETCOLOUR, &Ctest_device_sdkDlg::OnBnClickedButtonSetcolour)
	ON_BN_CLICKED(IDC_BUTTON_EXTCONFIG, &Ctest_device_sdkDlg::OnBnClickedButtonExtconfig)
	ON_BN_CLICKED(IDC_BUTTON_GETDEVINFO, &Ctest_device_sdkDlg::OnBnClickedButtonGetdevinfo)
END_MESSAGE_MAP()


// Ctest_device_sdkDlg 消息处理程序

Ctest_device_sdkDlg* g_dlg = NULL;

BOOL Ctest_device_sdkDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	m_pDecode = CreateDecode();
	m_pDecode->Init(NULL);
	m_nDec = -1;
	//m_pDecode->SetDecodeDataCallBack(FunDecodeDataCallBack, this);

	m_ctrlInfo.SetExtendedStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);
	m_ctrlInfo.InsertColumn(0, _T("info"), LVCFMT_LEFT, 1000);

	g_dlg = this;

	SetDlgItemText(IDC_EDIT_SERVERIP, _T("192.168.1.83"));
	SetDlgItemText(IDC_EDIT_SERVER_PORT, _T("7706"));
	SetDlgItemText(IDC_EDIT_DEVICEID, _T("10000"));
	//SetDlgItemText(IDC_EDIT_DEVICEID, _T("10003"));
	SetDlgItemText(IDC_EDIT_CHANNEL, _T("1"));

	m_bTalk = false;

	SetTimer(1, 1000, NULL);

	m_pFile = NULL;

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE

}

void Ctest_device_sdkDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void Ctest_device_sdkDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR Ctest_device_sdkDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


int CALLBACK OnEventCB(long long llUserData, const char* strEvent, int nEventType)
{
	//::OutputDebugStringA(strEvent);
	//::OutputDebugStringA("\r\n");

	TRACE("OnEventCB() - time %d   %s \r\n", ::GetTickCount(), strEvent);

	g_dlg->addInfo(strEvent);

	g_dlg->DealEvent(llUserData, strEvent, nEventType);

	return 0;
}


int CALLBACK OnFrameCB(SDS_Device::sdk::_handle stream, BYTE* lpBuf, int size, long long llStamp, int type, int channel, long long llUserData)
{
	TRACE(_T("OnFrameCB() - recv frame, hStream:0x%p, frame type x%x, size %d, timestamp %lld, channel %d, tick %d ---\r\n"),
		stream, type, size, llStamp, channel, ::GetTickCount());

	if (type == sds::device::em_FrameType_FileList_Frame )
	{
		::OutputDebugStringA((char*)lpBuf);
		::OutputDebugStringA("\r\n");
		g_dlg->addInfo((char*)lpBuf);
		return 0;
	}
	if (type == sds::device::em_FrameType_Status_Frame)
	{
		::OutputDebugStringA((char*)lpBuf);
		::OutputDebugStringA("\r\n");
		g_dlg->addInfo((char*)lpBuf);

		//g_dlg->OnBnClickedButtonCloseupgrade();
		g_dlg->PostMessage(WM_COMMAND, BN_CLICKED, (LPARAM)(g_dlg->GetDlgItem(IDC_BUTTON_CLOSEUPGRADE)->GetSafeHwnd()));

		return 0;
	}
	else if (type == sds::device::em_FrameType_Snap_Frame)
	{
		if (size <= 0)
			return 0;

		if (g_file == NULL)
			g_file = fopen("d:\\aaa.jpg", "wb");

		fwrite(lpBuf, 1, size, g_file);

		if (ftell(g_file) >= (long)llStamp)
		{
			fclose(g_file);
			g_file = NULL;
		}

		return 0;
	}
	else if (type == sds::device::em_FrameType_Data_Frame		||
			 type == sds::device::em_FrameType_Data2_Frame	||
			 type == sds::device::em_FrameType_Log_Frame)
	{
		if (size <= 0)
			return 0;

		if (g_file == NULL)
		{
			if (g_dlg->m_stDownloadRequest.nType == 1)		// jpg
				g_file = fopen("d:\\record saved\\aaa.jpg", "wb");
			else if (g_dlg->m_stDownloadRequest.nType == 2) // video
			{
				// there may be 4 channels video alarm occurred, but only one merged 
				// video file is generated by device we do not need to download 4 times
				DWORD dwResult = GetFileAttributes(_T("d:\\record saved\\aaa.cv1"));
				if (dwResult == INVALID_FILE_ATTRIBUTES)
				{
					g_file = fopen("d:\\record-saved\\aaa.cv1", "wb");
				}
			}
		}

		if (g_file != NULL)
		{
			fwrite(lpBuf, 1, size, g_file);
		}

		if (ftell(g_file) >= g_dlg->m_stDownloadRequest.llFileSize)
		//if (ftell(g_file) >= (long)llStamp)
		{
			fclose(g_file);
			g_file = NULL;
			::OutputDebugStringA("get down file finish  \r\n");
		}

		return 0;
	}

	Ctest_device_sdkDlg* pDlg = (Ctest_device_sdkDlg*)llUserData;
	if (type == sds::device::em_FrameType_Header_Frame)
	{
		pDlg->m_pDecode->InputDecodeStream(pDlg->m_nDec, 1, (BYTE*)lpBuf, size, llStamp);
		pDlg->m_pDecode->CtrlPlay(pDlg->m_nDec, 3, 1);
	}	
	else if (type == sds::device::em_FrameType_RHeader_Frame)
	{
		// playback
		//pDlg->m_objAvi.WriteAviFrame(0, 2, lpBuf, size);

		sds::device::pst_file_info p = (sds::device::pst_file_info)lpBuf; //当开始时间戳（微秒） + 时长（毫秒）<= 当前时间戳 ，即可结束
		if(p->uiVideoCodec == 0)//TTX_VIDEO_CODEC_H264
			pDlg->m_pDecode->InputDecodeStream(pDlg->m_nDec, 2, (BYTE*)lpBuf, size, llStamp);
		else
			pDlg->m_pDecode->InputDecodeStream(pDlg->m_nDec, 3, (BYTE*)lpBuf, size, llStamp);
	}
	else
	{
		pDlg->m_pDecode->InputDecodeStream(pDlg->m_nDec, type, (BYTE*)lpBuf, size, llStamp);
	}

	return 0;
}

void Ctest_device_sdkDlg::OnBnClickedButtonStart()
{
	// TODO: 在此添加控件通知处理程序代码
	char     szServerIp[32] = { 0 };
	char     szServerPort[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_SERVERIP, szServerIp, 32);
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_SERVER_PORT, szServerPort, 32);
	
	szServerPort[sizeof(szServerPort) - 1] = 0;
	int nPort = atoi(szServerPort);

	SDS_Device::sdk::st_work_param param;
	memset(&param, 0, sizeof(param));
	strcpy(param.server, szServerIp);
	param.port = nPort;
	param.callbackEvent = OnEventCB;
	param.callbackFrame = OnFrameCB;
	param.llUserData = (long long)this;
	SDS_Device::sdk::SDS_NetDevice_Init(param);	

	addInfo("server start!  ");
}

void Ctest_device_sdkDlg::OnBnClickedButtonStop()
{
	// TODO: 在此添加控件通知处理程序代码
	SDS_Device::sdk::SDS_NetDevice_Uninit();

	addInfo("server stop!  ");
}

SDS_Device::sdk::_handle stream = NULL;
void Ctest_device_sdkDlg::OnBnClickedButtonOpenstream()
{
	// TODO: 在此添加控件通知处理程序代码

	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);

	char	szChan[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_CHANNEL, szChan, 32);

	int nChan = atoi(szChan);

	//视频
	//video
	SDS_Device::sdk::SDS_NetDevice_OpenStream(szDeviceId, nChan, sds::device::eStreamType::eMainStream, stream);

	//音频
	//audio
	//SDS_Device::sdk::SDS_NetDevice_OpenStream(szDeviceId, 1, sds::device::eStreamType::eAudioStream, stream);
	m_nDec = m_pDecode->OpenDecodeChan(GetDlgItem(IDC_STATIC_VIDEO)->GetSafeHwnd(), 0);
	m_pDecode->CtrlPlay(m_nDec, 3, 1);
}

void Ctest_device_sdkDlg::OnBnClickedButtonClosestream()
{
	// TODO: 在此添加控件通知处理程序代码
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_CloseStream(stream);
		stream = NULL;
	}

	if (m_nDec != -1)
	{
		m_pDecode->CtrlPlay(m_nDec, 3, 0);
		m_pDecode->CloseDecodeChan(m_nDec);
		m_nDec = -1;
	}
}

BOOL Ctest_device_sdkDlg::DestroyWindow()
{
	// TODO: 在此添加专用代码和/或调用基类
	if (m_pDecode)
	{
		m_pDecode->Delete();
		m_pDecode = NULL;
	}

	KillTimer(1);

	return CDialogEx::DestroyWindow();
}

void Ctest_device_sdkDlg::addInfo(const char* strEvent)
{
	m_objLock.Lock();
	m_vtInfo.push_back(strEvent);

	if (m_vtInfo.size() > 20)
	{
		m_vtInfo.erase(m_vtInfo.begin());
	}
	m_objLock.Unlock();
}

void Ctest_device_sdkDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认值
	//::interlockede
	vector<string>		vtInfoTemp;
	m_objLock.Lock();
	vtInfoTemp = m_vtInfo;
	m_objLock.Unlock();

	m_ctrlInfo.DeleteAllItems();

	for (int i = 0; i < (int)vtInfoTemp.size(); i++)
	{
		m_ctrlInfo.InsertItem(m_ctrlInfo.GetItemCount(), (TCHAR*)_bstr_t(vtInfoTemp[i].c_str()));
	}

	if (m_bTalk)
	{
		char  audio_data[104] = { 0 };
		SDS_Device::sdk::SDS_NetDevice_TalkSend(stream, 0, (BYTE*)audio_data, 104);
	}

	CDialogEx::OnTimer(nIDEvent);
}

void Ctest_device_sdkDlg::OnBnClickedButtonOpentalk()
{
	// TODO: 在此添加控件通知处理程序代码

	m_nDec = m_pDecode->OpenDecodeChan(GetDlgItem(IDC_STATIC_VIDEO)->GetSafeHwnd(), 0);
	m_pDecode->CtrlPlay(m_nDec, 3, 1);

	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);

	SDS_Device::sdk::SDS_NetDevice_TalkStart(szDeviceId, 1, stream);

	m_bTalk = true;
}

void Ctest_device_sdkDlg::OnBnClickedButtonClosetalk()
{
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_TalkStop(stream);
		stream = NULL;
	}

	m_bTalk = false;

	if (m_nDec != -1)
	{
		m_pDecode->CtrlPlay(m_nDec, 3, 0);
		m_pDecode->CloseDecodeChan(m_nDec);
		m_nDec = -1;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonGetgps()
{
	SDS_Device::sdk::SDS_NetDevice_GetGPS(NULL, true);
}

void Ctest_device_sdkDlg::OnBnClickedButtonStopgps()
{
	SDS_Device::sdk::SDS_NetDevice_GetGPS(NULL, false);
}

void Ctest_device_sdkDlg::OnBnClickedButtonGetalarm()
{
	g_dlg->addInfo("subscribe alarm\r\n");
	SDS_Device::sdk::SDS_NetDevice_GetAlarm(NULL, true);
}

void Ctest_device_sdkDlg::OnBnClickedButtonStopalarm()
{
	SDS_Device::sdk::SDS_NetDevice_GetAlarm(NULL, false);
}

void Ctest_device_sdkDlg::OnBnClickedButtonQuery()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	SDS_Device::sdk::SDS_NetDevice_Query(szDeviceId, 1, "171222 000000", "235959",98, stream);
}

void Ctest_device_sdkDlg::OnBnClickedButtonClosequery()
{
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_CloseQuery(stream);
		stream = NULL;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonOpenreplay()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);

	// if the end position parameter is set to 0, it may replay the whole file.
	SDS_Device::sdk::SDS_NetDevice_ReplayStart(szDeviceId, 1, "/var/disk0/rec_file/rec0061.cv1", 0, 0, 0, stream);

	m_nDec = m_pDecode->OpenDecodeChan(GetDlgItem(IDC_STATIC_VIDEO)->GetSafeHwnd(), 0);
	m_pDecode->CtrlPlay(m_nDec, 3, 1);
}

void Ctest_device_sdkDlg::OnBnClickedButtonClosereplay()
{
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_ReplayStop(stream);
		stream = NULL;
	}

	if (m_nDec != -1)
	{
		m_pDecode->CtrlPlay(m_nDec, 3, 0);
		m_pDecode->CloseDecodeChan(m_nDec);
		m_nDec = -1;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonSnap()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	SDS_Device::sdk::SDS_NetDevice_Capture(szDeviceId, 3, stream);

}

void Ctest_device_sdkDlg::OnBnClickedButtonClosesnap()
{
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_CloseCapture(stream);
		stream = NULL;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonDownsnap()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	SDS_Device::sdk::SDS_NetDevice_DownloadSnap(szDeviceId, "/var/disk1/pic/2017-12-19/10002_175431_1.jpg", stream);
}

void Ctest_device_sdkDlg::OnBnClickedButtonClosedownsnap()
{
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_CloseDownloadSnap(stream);
		stream = NULL;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonUpgrade()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	SDS_Device::sdk::SDS_NetDevice_UpgradeStart(szDeviceId, "H:\\M21xx-APP-VH26501.crc", "M21xx-APP-VH26501.crc", stream); //V1703291
	//SDS_Device::sdk::SDS_NetDevice_UpgradeStart(szDeviceId, "H:\\M21xx-APP-V010213.crc", "M21xx-APP-V010213.crc", stream); //V1703291
}

void Ctest_device_sdkDlg::OnBnClickedButtonCloseupgrade()
{
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_UpgradeStop(stream);
		stream = NULL;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonGetiostatus()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	UINT nInputStatus;
	int nInputCount;
	UINT nOutputStatus;
	int nOutputCount;
	SDS_Device::sdk::SDS_NetDevice_GetIoStatus(szDeviceId, nInputStatus, nInputCount, nOutputStatus, nOutputCount);
}

void Ctest_device_sdkDlg::OnBnClickedButtonIoctrl()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	SDS_Device::sdk::SDS_NetDevice_Ctrl(szDeviceId, sds::device::eCtrlType::eCircuit_cutoff);
}

void Ctest_device_sdkDlg::OnBnClickedButtonPtz()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	//SDS_Device::sdk::SDS_NetDevice_PtzCtrl(szDeviceId, 1, sds::device::ePtzActionType::ePtzActionUp, 0, 0);
	SDS_Device::sdk::SDS_NetDevice_PtzCtrlOnStream(stream, sds::device::ePtzActionType::ePtzActionDown, 10, 10);
}

void Ctest_device_sdkDlg::OnBnClickedButtonPtzTwo()
{
	// TODO: 在此添加控件通知处理程序代码
	SDS_Device::sdk::SDS_NetDevice_PtzCtrlOnStream(stream, sds::device::ePtzActionType::ePtzActionUp, 10, 10);
}

void Ctest_device_sdkDlg::OnBnClickedButtonTrans()
{
	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	st_device_config InCfg;
	memset(&InCfg, 0, sizeof(InCfg));
	//strcpy(InCfg.cBuffer, "<VariCfgSec Action='DEVICE_SET'><stGSensor fFD_X='0.000000' fFD_XLimit='1.000000' fFD_Y='0.000000' fFD_YLimit='1.000000' fFD_Z='2.000000' fFD_ZLimit='4.000000' ucFD_AlarmEnable='0'/></VariCfgSec>");
	//strcpy(InCfg.cBuffer, "<Parameter><NETWORK_S Action = \"get\" LocalIP = \"?\" LocalMask = \"?\" LocalGateway = \"?\" LocalMac = \"?\" MainServerIP = \"?\" MainServerPort = \"?\" SlaveServerIP = \"?\" SlaveServerPort = \"?\" VideoCenterIP = \"?\" VideoCenterPort = \"?\" VideoProtocol = \"?\" WifiSwitch = \"?\" SelectNet = \"?\" WifiEncrytion = \"?\" WifiEncrytionType = \"?\" WifiIP = \"?\" SubnetMask = \"?\" WifiGateway = \"?\" WifiSSID = \"?\" WifiSecretKey = \"?\" MIDFunction = \"?\" MIDType = \"?\" MIDCenterNum = \"?\" MIDAp = \"?\" MIDUsername = \"?\" MIDPassword = \"?\" / >< / Parameter>");
	
	strcpy(InCfg.cBuffer, "<VariCfgSec Action = \"DEVICE_QUERY\"><stVersion/></VariCfgSec>");
	InCfg.nLength = strlen(InCfg.cBuffer);
	st_device_config OutCfg;
	memset(&OutCfg, 0, sizeof(OutCfg));
	SDS_Device::sdk::SDS_NetDevice_TranConfig(szDeviceId, 0, &InCfg, &OutCfg);
	int kk = 0;
}

/*
int CALLBACK OnClientEvent(long long llUserData, const char* strEvent, int event_type)
{
	::OutputDebugStringA(strEvent);
	::OutputDebugStringA("\r\n");
	if (g_dlg)
		g_dlg->addInfo(strEvent);

	return 0;
}
*/

void Ctest_device_sdkDlg::OnBnClickedButtonSearch()
{
	// TODO: 在此添加控件通知处理程序代码
	SDS_Device::sdk::SDS_NetDevice_Search(6688);
}

void Ctest_device_sdkDlg::OnBnClickedButtonStopsearch()
{
	// TODO: 在此添加控件通知处理程序代码
	SDS_Device::sdk::SDS_NetDevice_StopSearch();
}

void Ctest_device_sdkDlg::OnBnClickedButtonDirectopenstream()
{
	// TODO: 在此添加控件通知处理程序代码
	m_nDec = m_pDecode->OpenDecodeChan(GetDlgItem(IDC_STATIC_VIDEO)->GetSafeHwnd(), 0);
	m_pDecode->CtrlPlay(m_nDec, 3, 1);

	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);

	SDS_Device::sdk::SDS_NetDevice_DirectOpenStream("192.168.1.10", 6688, 1, sds::device::eSubStream, stream);
}

void Ctest_device_sdkDlg::OnBnClickedButtonDirectclosestream()
{
	// TODO: 在此添加控件通知处理程序代码
	if (stream)
	{
		SDS_Device::sdk::SDS_NetDevice_DirectStopStream(stream);
		stream = NULL;
	}

	if (m_nDec != -1)
	{
		m_pDecode->CtrlPlay(m_nDec, 3, 0);
		m_pDecode->CloseDecodeChan(m_nDec);
		m_nDec = -1;
	}
}

void Ctest_device_sdkDlg::OnBnClickedButtonDirectptz()
{
	// TODO: 在此添加控件通知处理程序代码
	SDS_Device::sdk::SDS_NetDevice_DirectPtzCtrl("192.168.1.10", 6688, 1, sds::device::ePtzActionUp, 10, 0);
}

void Ctest_device_sdkDlg::OnBnClickedButtonGetcolour()
{
	// TODO: 在此添加控件通知处理程序代码
	int exposure = 128;
	int brightness = 128;
	int contrast = 0; 
	int hue = 0;
	int saturation = 128;
	SDS_Device::sdk::SDS_NetDevice_GetColourParam("10002", 1, exposure, brightness, contrast, hue, saturation);
	int kk = 0;
}

void Ctest_device_sdkDlg::OnBnClickedButtonSetcolour()
{
	// TODO: 在此添加控件通知处理程序代码
	int exposure = 128;
	int brightness = 128;
	int contrast = 0;
	int hue = 0;
	int saturation = 128;
	SDS_Device::sdk::SDS_NetDevice_SetColourParam("10002", 1, exposure, brightness, contrast, hue, saturation);
	int kk = 0;
}

BOOL CALLBACK funTransparentConfig(int nType, MDVRConfigData_S* lpInConfig, MDVRConfigData_S* lpOutConfig, void* pUsr)
{
	memset(lpOutConfig, 0, sizeof(MDVRConfigData_S));
	SDS_Device::sdk::SDS_NetDevice_TranConfig("10002", 0, (pst_device_config)lpInConfig, (pst_device_config)lpOutConfig);
	return TRUE;
}

//@ bInput: TRUE表示导入配置文件，会将szCfgFile传到设备上
//			FALSE表示导出配置文件，上层会从设备上获取szCfgFile，然后传给参数模块
//@ szCfgFile: 配置文件绝对路径，此文件名由参数模块生成
BOOL CALLBACK funLoadConfigFile(BOOL bInput, const char* szCfgFile, void* pUsr)
{
	return TRUE;
}

void Ctest_device_sdkDlg::OnBnClickedButtonExtconfig()
{
	// TODO: 在此添加控件通知处理程序代码
	std::string strLang = "d:\\sdk\\demo\\Language\\chinese";
	MDVR_SetConfigFunction(funTransparentConfig, funLoadConfigFile, this);
	MDVR_SetLangPath(strLang.c_str());
	MDVR_DisplayConfig(GetDlgItem(IDC_STATIC_VIDEO)->GetSafeHwnd(), NULL);
	MDVR_ActivePage();
}

void Ctest_device_sdkDlg::OnBnClickedButtonGetdevinfo()
{
	// TODO: 在此添加控件通知处理程序代码

	char     szDeviceId[32] = { 0 };
	::GetDlgItemTextA(this->GetSafeHwnd(), IDC_EDIT_DEVICEID, szDeviceId, 32);
	SDS_Device::sdk::SDS_NetDevice_RequestDeviceInfo(szDeviceId);
}
int Ctest_device_sdkDlg::DealEvent(long long llUserData, const char* strEvent, int nEventType)
{
	if (nEventType == sds::device::NETEVENT_NOTIFY)
	{
		// get video file path on device
		st_event_download_file stRequest = { 0 };
		AnalyzeJsonEvent(nEventType, strEvent, &stRequest);

		if (strlen(stRequest.szSourcePath) != 0)
		{
			if (stRequest.nType == 1)		// jpg
				DownloadFile(&stRequest);
			else if (stRequest.nType == 2)	// video
				DownloadVideo(&stRequest);
		}
	}

	return 0;
}

// [in] szEvent: event from device
// [out] strVideoPath: get the alarm video file path on device
int Ctest_device_sdkDlg::AnalyzeJsonEvent(int nEventType, const char *szEvent, st_event_download_file *pRequest)
{
	// TODO: Add your implementation code here.
	if (!szEvent || !pRequest) return 0;

	// alarm notify event
	int nRet = -1;

	//
	// here is only to keep demo simple, customer can use Json 
	// analyzing component to analyze event string
	//
	std::string strEvent = szEvent;
	std::string strVideoPath;

	Json::Reader reader;
	Json::Value root;
	if (reader.parse(szEvent, root))  
	{
		int nSubAlarmType = root["subalarmtype"].asInt();
		
		// file upload alarm
		if (nSubAlarmType == 19)
		{
			// picpath is file path	
			std::string strPicPath = root["picpath"].asString();  
			if (strPicPath.empty()) return nRet;

			strcpy(pRequest->szSourcePath, strPicPath.c_str());

			// device id
			std::string strDeviceId = root["deviceid"].asString();
			strcpy(pRequest->deviceId, strDeviceId.c_str());

			//
			pRequest->llFileSize = root["filelen"].asUInt();
			pRequest->nType = root["filetype"].asInt();	// 1 jpg, 2 video:cv1
			nRet = 0;
		}
	}

	return nRet;
}

int Ctest_device_sdkDlg::DownloadVideo(st_event_download_file *pRequest)
{
	if (!pRequest) return -1;

	pRequest->center = 0;
	pRequest->llBlockLen = 32 * 1024;
	pRequest->llStartOffset = 0;

	TRACE("DownloadFile() - device id:%s, file:%s, length:%lld", pRequest->deviceId, pRequest->szSourcePath, pRequest->llFileSize);

	m_stDownloadRequest = *pRequest;
	m_hDownload = NULL;
	int nRet = SDS_Device::sdk::SDS_NetDevice_DownloadFile2(pRequest->deviceId, pRequest->szSourcePath, m_hDownload);
	return 0;
}

int Ctest_device_sdkDlg::DownloadFile(st_event_download_file *pRequest)
{
	if (!pRequest) return -1;

	pRequest->center = 0;
	pRequest->llBlockLen = 32 * 1024;
	pRequest->llStartOffset = 0;
	
	TRACE("DownloadFile() - device id:%s, file:%s, length:%lld", pRequest->deviceId, pRequest->szSourcePath, pRequest->llFileSize);

	m_stDownloadRequest = *pRequest;
	m_hDownload = NULL;
	int nRet = SDS_Device::sdk::SDS_NetDevice_DownloadFile2(pRequest->deviceId, pRequest->szSourcePath, m_hDownload);
	return 0;
}
